//
//  OAuthViewController.swift
//  Weibo
//
//  Created by apple on 15/12/15.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
//App Key：1164276985
//App Secret：0f7c60b79e1251b7212f364e0f055053
class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
        setNavBar()
    }
    //加载授权页面
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string:urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
        
    }
    
    //设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    }
    
    //销毁控制器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充账号
    @objc private func defaultAccount() {
        let jsString = "document.getElementById('userId').value = '18263368259' ,document.getElementById('passwd').value = 'leon215256753'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    
}

//webView 代理方法
extension OAuthViewController:UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //根据请求的url 去加载希望加载的页面
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com/") {
            //希望加载的页面
            return true
        }
        
        if !urlString.hasPrefix("http://www.baidu.com") {
            //不希望加载的页面
            return false
        }
        //print(urlString)
        //走到这里一定是请求成功的回掉
        //获取url参数部分的键值
        let query = request.URL?.query
        //print(query)
        if let q = query {
            //截取字符串
            let codeString = "code="
            let code = q.substringFromIndex(codeString.endIndex)
            //print(code)
            //加载token
            loadAccessToken(code)
        }
        return false
    }
    //加载用户的token 请求标识
    private func loadAccessToken(code:String) {
        
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                
                //动画结束的时候 发出 页面切换的通知
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                self.close()
                print("登陆成功")
            }else {
                print("登陆失败")
            }
        }
        
    }
    
    
}

